from System import *
from System.Net import *
from System.Text import *
from System.Collections import *
from System.Collections.Specialized import *
from System.Windows.Media.Imaging import *

URLS = {
		"auth" : "http://twitter.com/account/verify_credentials.json",
		"friends" : "http://twitter.com/statuses/friends_timeline.json",
		"update" : "http://twitter.com/statuses/update.json",
		"search" : "http://search.twitter.com/search.json"
}

class Twitter:
	""" I deal with talking to Twitter. """
	def __init__(self):
	    self.hash = ""
	    self.presenters = []

	def credentials(username, password):
	    utf8 = UTF8Encoding();
	    self.hash = Convert.ToBase64String(utf8.GetBytes("%s:%s" % (username,password)))

	def add_presenter(self, presenter_instance):
	    self.presenters.append(presenter_instance)

	def friends_timeline(self):
		""" I get your friends' update """
		url = "%s" % URLS["friends"]
		self.fetch(url)

	def update(self, msg):
		""" I make updates for you. """
		url = "%s?status=%s" % (URLS["update"], msg)
		self.fetch(url, "POST")

	def search(self, query_terms):
	    """ Search for anything you want. I'll find it. You choose how to use the results. """
	    url = "%s?q=%s" % (URLS["search"], query_terms)
	    self.fetch(url)

	def update_status_list(self, sender, args):
		if(args.Error == None):
			resp = JsonValue.Parse(args.Result)
			for presenter in self.presenters:
				presenter.add_to_status_list(resp)
		else:
			log(args.Error)

	def fetch(self, uri, method="GET"):
		client = WebClient()
		proxy = str("http://localhost/gestalt/TwitterProxy.ashx?u=%s&m=%s" % (HttpUtility.UrlEncode(uri), HttpUtility.UrlEncode(method)))
		if(self.hash):
		    proxy += "&ph=%s" % HttpUtility.UrlEncode(self.hash)
		client.DownloadStringAsync(Uri(proxy))
		client.DownloadStringCompleted += self.update_status_list